<template>
  <span>
    <el-tag
      :key="tag"
      v-for="tag in dynamicTags"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)">
      {{tag}}
    </el-tag>
    <el-input
      class="input-new-tag"
      v-if="inputVisible"
      v-model="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    >
    </el-input>
    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ &nbsp;添加</el-button>
  </span>
</template>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
  margin-top: 5px;
  margin-bottom: 5px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

<script>
export default {
  props: {
    value: {}
  },
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      valIsString: false
    };
  },
  watch: {
    value(val){
      this.checkValIsString(val)
      if(this.valIsString){
        this.dynamicTags = val.split(',')
      }
    },
    dynamicTags(val){
      if(this.valIsString){
        this.$emit('input', val.join(','))
      } else {
        this.$emit('input', val)
      }
    }
  },
  methods: {
    checkValIsString(val){
      this.valIsString = (typeof val === 'string') || val == null
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
  },
  mounted() {
    this.checkValIsString(this.value)
  }
}
</script>
